package com.example.lib_yaorouter

import android.app.Activity
import android.content.Intent

/**
 * @author yaotianxue
 * @description
 * @date 2025/1/8
 */
class YaoRouter {
    private constructor() //构造私有化

    companion object{
        //双重校验锁单例模式：
        private var instance:YaoRouter? = null
        fun getInstance():YaoRouter{
            if (instance == null){
                synchronized(YaoRouter::class.java){
                    if (instance == null){
                        instance = YaoRouter()
                    }
                }
            }
            return instance!!
        }
    }
    //home组：   (/home/HomeActivity,HomeActivity.class)，(/home/VideoActivity,VideoActivity.class) 。。。。
    //user组：   (/user/UserActivity,UserActivity.class)，(/user/VideoActivity,VideoActivity.class) 。。。。
    //main组：  (/main/MainActivity,MainActivity.class)，(/main/VideoActivity,VideoActivity.class) 。。。。
    //路由表 键：group的名字 值：组map
    val groupMap: MutableMap<String,MutableMap<String,Class<*>>> = mutableMapOf()

    /**
     * path:路径  /home/HomeActivity
     * clazz：Class对象
     */
    fun register(path:String,clazz:Class<*>){

        var strArray= path.split("/")
        if(strArray.size > 2){
            val groupName = strArray[1]
            var  group :MutableMap<String,Class<*>>?
            if(groupMap.containsKey(groupName)){ //有
                group = groupMap[groupName]
            }else{//没有
                group = HashMap<String,Class<*>>()
                groupMap[groupName] = group
            }
            group?.set(path, clazz)
        }
    }

    /**
     * 页面跳转
     */
    fun startActivity(path:String,activity: Activity){
        var strArray= path.split("/")
        if(strArray.size > 2){
            val groupName = strArray[1]
            var  group :MutableMap<String,Class<*>>? = null
            if(groupMap.containsKey(groupName)){ //有
                group = groupMap[groupName]
            }
            if( group != null && group?.containsKey(path) == true){
                val clazz: Class<*>? = group[path]
                activity.startActivity(Intent(activity,clazz))
            }

        }
    }




}